'use strict'

import { app, protocol, BrowserWindow, Menu, ipcMain, globalShortcut, session, powerSaveBlocker, Tray, dialog } from 'electron'
import { createProtocol } from 'vue-cli-plugin-electron-builder/lib'
import installExtension, { VUEJS3_DEVTOOLS } from 'electron-devtools-installer'
const path = require('path');
import axios from 'axios';
import { autoUpdater } from 'electron-updater'
const { exec } = require('child_process');
const os = require('os');

const { createheyueList, createRightClickmneun, hiderightClickMenu, createdadanFazhi, createklineStartDate, createzijinLiushui, createhuaxiadanOption, createsunYing, creategongggaoinfo, createuserevaluate, createabout, createuploadlog, createruntimelog, createchedanview, createnetworkcondition, createpreferredmarketserver, createStopLossOpen, createConditionList, createhuaxianlist, createyujinglist, createyujingchufalist, createanjian, createRegister } = require('./windowView');


Menu.setApplicationMenu(null);

let winURL
if (process.env.WEBPACK_DEV_SERVER_URL) {
  winURL = process.env.WEBPACK_DEV_SERVER_URL
} else {
  winURL = 'app://./index.html'
}

const isDevelopment = process.env.NODE_ENV !== 'production'
protocol.registerSchemesAsPrivileged([
  { scheme: 'app', privileges: { secure: true, standard: true } }
])
let loadingView
async function createLoadingView() {
  powerSaveBlocker.start('prevent-app-suspension')
  loadingView = new BrowserWindow({
    width: 660,
    height: 360,
    frame: false,
    resizable: false,
    maximizable: false,  // 禁止最大化
    minimizable: false,  // 禁止最小化
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
      zoomFactor: 1.0,
    }
  })
  loadingView.hide()
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    loadingView.loadURL(process.env.WEBPACK_DEV_SERVER_URL)
  } else {
    createProtocol('app')
    loadingView.loadURL('app://./index.html')
  }
  loadingView.on('close', () => {
    loadingView = null
  })
  loadingView.webContents.on('did-finish-load', () => {
    if (loadingView) loadingView.show()
    autoUpdateInit()
  })
}

let win, exitWindow
async function createWindow() {
  win = new BrowserWindow({
    width: 1400,
    height: 710,
    frame: false,
    minWidth: 1210,
    minHeight: 710,
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
    }
  })
  win.hide()
  win.on('resize', () => {
    const [width, height] = win.getSize();
    win.webContents.send('window-resize', { width, height });
  });
  await win.loadURL(winURL + '#/indexHome');
  await createLogin();
  await createhuaxiadanOption(win)
  await createhuaxianlist(win)
  await createyujinglist(win)
  await createyujingchufalist(win)
  await createanjian(win)
  await createRegister(loginWindow)

  createRightClickmneun(win, loadingView)
  win.on('close', (e) => {
    if (!exitWindow) {
      e.preventDefault();
      createExitWindow();
    }
  });
}
// 退出窗口
function createExitWindow() {
  exitWindow = new BrowserWindow({
    width: 310,
    height: 184,
    parent: win,
    modal: true,
    resizable: false,
    maximizable: false,  // 禁止最大化
    minimizable: false,  // 禁止最小化
    title: '提示',  // 设置窗口标题
    icon: '',  // 去掉图标
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });

  if (process.env.WEBPACK_DEV_SERVER_URL) {
    exitWindow.loadFile(path.join(__dirname, '../src/assets/html/exit.html'));
  } else {
    exitWindow.loadFile(path.join(__dirname, '../assets/html/exit.html'));
  }
  exitWindow.on('close', () => {
    globalShortcut.unregister('Alt+Shift+Ctrl+M');
    globalShortcut.unregister('F5');
    globalShortcut.unregister('Alt+Shift+Ctrl+N');
    exitWindow = null;
  });
}

// 画线窗口
let huaTuWindow
function createHuaTuGj(v) {
  huaTuWindow = new BrowserWindow({
    width: 250,
    height: 450,
    parent: win,
    modal: true,
    resizable: false,
    maximizable: false,  // 禁止最大化
    minimizable: false,  // 禁止最小化
    title: '提示',  // 设置窗口标题
    icon: '',  // 去掉图标
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    huaTuWindow.loadFile(path.join(__dirname, '../src/assets/html/huatugongju.html'));
  } else {
    huaTuWindow.loadFile(path.join(__dirname, '../assets/html/huatugongju.html'));
  }
  huaTuWindow.on('close', () => {
    huaTuWindow = null
  })
  huaTuWindow.webContents.on('did-finish-load', () => {
    huaTuWindow.webContents.send('huaTuNumber', v);
  });
}

ipcMain.on('createHuaTuGj', (e, v) => {
  createHuaTuGj(v);
});
ipcMain.on('closeHuaTuGj', (e, v) => {
  huaTuWindow.close()
  huaTuWindow = null
  win.webContents.send('edithuaTuGj', v)
});

ipcMain.on('open-right-click', (e, v) => {
  createRightClickmneun(win, loadingView, v)
});

ipcMain.on('right_click_msg', (e, v) => {
  win.webContents.send('right_click_msg_win', v)
});
ipcMain.on('placeAnOrderWindow_click_msg', (e, v) => {
  placeAnOrderWindow.webContents.send('right_click_msg_win', v)
});
ipcMain.on('open-dadanFazhi', (e, v) => {
  createdadanFazhi(win)
});
ipcMain.on('open-klineStartDate', (e, v) => {
  createklineStartDate(win)
});
ipcMain.on('open-huaxiadanOption', (e, v) => {
  if (placeAnOrderWindow) {
    createhuaxiadanOption(win)
  } else {
    createLogin(v);
  }
});
ipcMain.on('hua_xian_xia_dan_data', (e, v) => {
  if (placeAnOrderWindow) placeAnOrderWindow.webContents.send('hua_xian_xia_dan_data', v)
});
ipcMain.on('open-gonggaoinfo', (e, v) => {
  creategongggaoinfo(placeAnOrderWindow, v)
});
ipcMain.on('open-userevaluate', (e, v) => {
  createuserevaluate(win)
});
ipcMain.on('open-about', (e, v) => {
  createabout(win)
});
ipcMain.on('open-chedanview', (e, v) => {
  createchedanview(win, v)
});
ipcMain.on('close-exe', (e, v) => {
  win.setSkipTaskbar(true);
  win.hide()
});
ipcMain.on('open-networkcondition', (e, v) => {
  win.webContents.send('running_time', process.uptime())
  createnetworkcondition(win, v)
});
ipcMain.on('open-preferredmarketserver', (e, v) => {
  createpreferredmarketserver(win)
});
ipcMain.on('open-yujinglist', (e, v) => {
  createyujinglist(win)
});
ipcMain.on('open-yujingchufalist', (e, v) => {
  createyujingchufalist(win)
});
ipcMain.on('open-anjian', (e, v) => {
  createanjian(win, v)
});
ipcMain.on('open-register', (e, v) => {
  createRegister(loginWindow)
});
ipcMain.on('open-huaxianlist', (e, v) => {
  if (placeAnOrderWindow) {
    createhuaxianlist(win)
  } else {
    createLogin(v);
  }
});
ipcMain.on('change-imized', (e, v) => {
  if (win.isMaximized()) {
    win.unmaximize(); // 如果窗口已经最大化，则取消最大化
  } else {
    win.maximize(); // 否则窗口最大化
  }
});
ipcMain.on('ping-command', async (event, url) => {
  console.log(`output->`, 'ping ' + url)
  exec('ping ' + url, (error, stdout, stderr) => {
    if (stderr || error) {
      win.webContents.send('right_click_msg_win', { type: 'ping服务器失败' })
      return;
    }
    event.reply('ping-result', stdout); // 将结果发送给渲染进程
  });
});

// 清除所有缓存
ipcMain.on('clear_all_cache', (e, v) => {
  session.defaultSession.clearStorageData({
    storages: ['localstorage']
  }).then(() => {
    if (win) win.reload();
    if (placeAnOrderWindow) {
      placeAnOrderWindow.close()
      placeAnOrderWindow = null
    }
    if (loginWindow) loginWindow.hide()
    hiderightClickMenu()
  });
});


// 登录窗口
let loginWindow, orderStatus
function createLogin(v) {
  if (placeAnOrderWindow) {
    if (v.orderStatus) {
      win.webContents.send('right_click_msg_win', { type: '下单工具条', msg: v.orderStatus })
    } else {
      placeAnOrderWindow.focus()
    }
    return
  }
  if (loginWindow) {
    loginWindow.webContents.send('config_Info', v.configInfo)
    loginWindow.show()
    return
  }
  loginWindow = new BrowserWindow({
    width: 560,
    height: 335,
    modal: true,
    frame: false,
    parent: win,
    resizable: false,
    maximizable: false,  // 禁止最大化
    minimizable: false,  // 禁止最小化
    title: '提示',  // 设置窗口标题.
    icon: '',  // 去掉图标
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });
  loginWindow.hide()
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    loginWindow.loadFile(path.join(__dirname, '../src/assets/html/login.html'));
  } else {
    loginWindow.loadFile(path.join(__dirname, '../assets/html/login.html'));
  }
  loginWindow.on('close', () => {
    loginWindow = null
  })
}

// 下单窗口
var placeAnOrderWindow
function createPlaceAnOrder(v) {
  placeAnOrderWindow = new BrowserWindow({
    width: 1280,
    height: 345,
    minHeight: 345,
    minWidth: 1280,
    modal: true,
    frame: false,
    resizable: true,
    maximizable: false,  // 禁止最大化
    minimizable: false,  // 禁止最小化
    icon: '',  // 去掉图标
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true
    }
  });
  // placeAnOrderWindow.openDevTools()
  placeAnOrderWindow.on('resize', () => {
    const [width, height] = placeAnOrderWindow.getSize();
    placeAnOrderWindow.webContents.send('placeAnOrderWindow-resize', { width, height });
  });
  if (orderStatus) {
    win.webContents.send('right_click_msg_win', { type: '下单工具条', msg: orderStatus })
    placeAnOrderWindow.minimize()
  }
  placeAnOrderWindow.setAlwaysOnTop(true);//窗口置顶
  placeAnOrderWindow.loadURL(winURL + '#/xiadan');
  placeAnOrderWindow.on('close', () => {
    placeAnOrderWindow = null
  })
  placeAnOrderWindow.webContents.on('did-finish-load', () => {
    placeAnOrderWindow.webContents.send('placeAnOrder', v);
    createStopLossOpen(placeAnOrderWindow)
  });
  createzijinLiushui(placeAnOrderWindow)
  createConditionList(placeAnOrderWindow)
}

ipcMain.on('createLogin', (e, v) => {
  orderStatus = v.orderStatus
  createLogin(v);
});
ipcMain.on('minplaceAnOrder', (e, v) => {
  placeAnOrderWindow.minimize()
});
ipcMain.on('closeplaceAnOrder', (e, v) => {
  if (loginWindow) loginWindow.hide()
  if (placeAnOrderWindow) placeAnOrderWindow.webContents.send('close-msg')
  if (placeAnOrderWindow) placeAnOrderWindow.close()
  placeAnOrderWindow = null
  win.webContents.send('networkdetail-log', '软件退出登录');
});
ipcMain.on('focus-order', (e, v) => {
  if (placeAnOrderWindow) placeAnOrderWindow.focus()
});
ipcMain.on('send-placeAnOrder', (e, v) => {
  if (placeAnOrderWindow) placeAnOrderWindow.webContents.send('select-heyue', v);
});
ipcMain.on('closeLogin', (e, v) => {
  if (v.type == 2) {
    if (placeAnOrderWindow) {
      placeAnOrderWindow.close()
      placeAnOrderWindow = null
    }
    createPlaceAnOrder(v)
  }
  loginWindow.hide()
});

ipcMain.on('oepnHeyueList', () => {
  createheyueList(placeAnOrderWindow)
});
ipcMain.on('oepn-zijinLiushui', (e, v) => {
  createzijinLiushui(placeAnOrderWindow, v)
});
ipcMain.on('oepn-sunYing', (e, v) => {
  createsunYing(placeAnOrderWindow, v)
});

ipcMain.on('oepn-uploadlog', (e, v) => {
  createuploadlog(win)
});
ipcMain.on('open-runtime-log', (e, v) => {
  createruntimelog(win)
});

ipcMain.on('set-networkdetail-log', (e, v) => {
  win.webContents.send('networkdetail-log', v);
});


ipcMain.on('open-screenshot', async (e, v) => {
  exec('snippingtool', (error, stdout, stderr) => {
    if (error) {
      console.error(`Error executing screenshot: ${error}`);
      return;
    }
    console.log(`Screenshot tool stdout: ${stdout}`);
  });
});




app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') {
    globalShortcut.unregister('Alt+Shift+Ctrl+M');
    globalShortcut.unregister('F5');
    globalShortcut.unregister('Alt+Shift+Ctrl+N');
    app.quit()
  }
})

app.on('activate', () => {
  if (BrowserWindow.getAllWindows().length === 0) createLoadingView()
})
app.on('ready', async () => {
  protocol.registerFileProtocol('custom', (request, callback) => {
    const filePath = request.url.replace('custom://', '');
    const decodedFilePath = decodeURI(filePath);
    callback({ path: decodedFilePath });
  });
  setTray()
  if (isDevelopment && !process.env.IS_TEST) {
    try {
      await installExtension(VUEJS3_DEVTOOLS)
    } catch (e) {
      console.error('Vue Devtools failed to install:', e.toString())
    }
  }
  globalShortcut.register('Alt+Shift+Ctrl+M', () => {
    if (win) win.webContents.openDevTools()
  })
  globalShortcut.register('Alt+Shift+Ctrl+N', () => {
    if (placeAnOrderWindow) placeAnOrderWindow.webContents.openDevTools()
    if (loginWindow) loginWindow.webContents.openDevTools()
  })

  globalShortcut.register('F5', () => {
    if (win) win.reload();
    if (placeAnOrderWindow) {
      placeAnOrderWindow.close()
      placeAnOrderWindow = null
    }
    if (loginWindow) loginWindow.hide()
    hiderightClickMenu()
  })
  createLoadingView()
})
ipcMain.on('close-main-window', () => {
  if (win) {
    win.webContents.send('running_time', process.uptime())
    ipcMain.removeAllListeners();
    const windows = BrowserWindow.getAllWindows();
    windows.forEach(allwin => {
      if (allwin && !allwin.isDestroyed()) {
        allwin.destroy(); // 强制销毁窗口
      }
    });
    app.quit()
  }
});
app.on('browser-window-focus', () => {
  globalShortcut.register('Alt+Shift+Ctrl+M', () => {
    if (win) win.webContents.openDevTools()
  })
  globalShortcut.register('Alt+Shift+Ctrl+N', () => {
    if (placeAnOrderWindow) placeAnOrderWindow.webContents.openDevTools()
    if (loginWindow) loginWindow.webContents.openDevTools()
  })
  globalShortcut.register('F5', () => {
    if (win) win.reload();
    if (placeAnOrderWindow) {
      placeAnOrderWindow.close()
      placeAnOrderWindow = null
    }
    if (loginWindow) loginWindow.hide()
    hiderightClickMenu()
  })
})
if (isDevelopment) {
  if (process.platform === 'win32') {
    process.on('message', (data) => {
      if (data === 'graceful-exit') {
        app.quit()
      }
    })
  } else {
    process.on('SIGTERM', () => {
      app.quit()
    })
  }
}

// 软件检查更新 
async function autoUpdateInit() {
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    return createWindow()
  }
  // let { data } = await axios.get('https://ceshi1.zchczz.com/khd/config.json?fff=333')
  // let { data } = await axios.get('https://ceshi1.zchczz.com/khd/config.json?fff=' + new Date() / 1)
  let { data } = await axios.get('http://146.56.245.135:8098/khd/config.json?fff=' + new Date() / 1)
  let httpType = 'http://'
  if (data.is_ssl == 1) {
    httpType = 'https://'
  }
  data.uploadUrl = httpType + data.uploadUrl
  autoUpdater.setFeedURL({ provider: 'generic', url: data.uploadUrl, channel: process.env.VUE_APP_LATEST_NAME });
  autoUpdater.disableWebInstaller = false
  autoUpdater.autoDownload = false //这个必须写成false，写成true时，我这会报没权限更新，也没清楚什么原因
  const checkForUpdates = autoUpdater.checkForUpdatesAndNotify();
  if (!checkForUpdates) createWindow()
  //  没有更新
  autoUpdater.on('update-not-available', () => {
    createWindow()
  })
  //  发生错误时
  autoUpdater.on('error', (error) => {
    createWindow()
  })
  // 发现可更新数据时
  autoUpdater.on('update-available', (info) => {
    autoUpdater.downloadUpdate()
  })
  // 下载监听
  autoUpdater.on('download-progress', (progress) => {
    loadingView.webContents.send('downloadEvent', progress)
  })
  // 下载完成
  autoUpdater.on('update-downloaded', () => {
    autoUpdater.quitAndInstall()
  })

}
var tray = null;
function setTray() {
  // 创建系统托盘图标
  let imgstr = ''
  if (process.env.WEBPACK_DEV_SERVER_URL) {
    imgstr = path.join(__dirname, '../src/assets/logo.png')
  } else {
    imgstr = path.join(__dirname, '../assets/logo.png')
  }
  tray = new Tray(imgstr); // 替换成你自己的图标路径
  const contextMenu = Menu.buildFromTemplate([
    {
      label: '显示窗口',
      click: () => {
        win.show();
        win.setSkipTaskbar(false); // 显示时恢复到任务栏
      }
    },
    {
      label: '隐藏窗口',
      click: () => {
        win.hide();
        win.setSkipTaskbar(true); // 隐藏时从任务栏中移除
      }
    },
    {
      label: '退出',
      click: () => {
        win.close();
      }
    }
  ]);

  // 设置托盘菜单
  tray.setContextMenu(contextMenu);

  // 当用户单击托盘图标时的行为
  tray.setToolTip('Electron 应用在后台运行');
  tray.on('click', () => {
    if (win.isVisible()) {
      win.hide();
      win.setSkipTaskbar(true); // 隐藏并从任务栏移除
    } else {
      win.show();
      win.setSkipTaskbar(false); // 显示并恢复到任务栏
    }
  });
}

let highCpuSeconds = 0;

// 获取 CPU 占用率
function getCpuUsage() {
  const cpus = os.cpus();
  let idle = 0;
  let total = 0;

  cpus.forEach((cpu) => {
    for (let type in cpu.times) {
      total += cpu.times[type];
    }
    idle += cpu.times.idle;
  });

  const usage = 1 - idle / total;
  return usage * 100; // 返回百分比
}

// 监控 CPU 占用率
function monitorCpuUsage() {
  setInterval(() => {
    const usage = getCpuUsage();

    // 如果 CPU 占用率超过 50%，累加秒数
    if (usage > 50) {
      highCpuSeconds += 1;
    }

    // 每 60 秒计算一次超过 50% 的分钟数，并发送给渲染进程
    if (highCpuSeconds % 60 === 0) {
      const highCpuMinutes = Math.floor(highCpuSeconds / 60);
      win.webContents.send('cpu-usage-high-minutes', highCpuMinutes);
    }
    if (highCpuSeconds % 600 === 0) {
      win.webContents.send('networkdetail-log', 'CPU占用过高');
    }
  }, 1000); // 每秒检查一次
}
